package com.huaao.micropolice.root.controllers.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.google.gson.Gson;
import com.huaao.micropolice.common.util.JsonUtil;
import com.huaao.micropolice.core.common.gson.GsonSimpleFilter;
import com.huaao.micropolice.core.common.page.Page;
import com.huaao.micropolice.core.model.content.Subject;
import com.huaao.micropolice.core.model.system.Button;
import com.huaao.micropolice.core.model.system.Dept;
import com.huaao.micropolice.core.model.system.Jobs;
import com.huaao.micropolice.core.model.system.Menu;
import com.huaao.micropolice.core.model.system.Role;
import com.huaao.micropolice.core.model.system.User;
import com.huaao.micropolice.core.service.content.SubjectService;
import com.huaao.micropolice.core.service.system.ButtonService;
import com.huaao.micropolice.core.service.system.DeptService;
import com.huaao.micropolice.core.service.system.JobsService;
import com.huaao.micropolice.core.service.system.MenuDeptService;
import com.huaao.micropolice.core.service.system.MenuService;
import com.huaao.micropolice.core.service.system.MenuSubjectService;
import com.huaao.micropolice.core.service.system.RoleService;
import com.huaao.micropolice.core.service.system.UserService;
import com.huaao.micropolice.root.commons.TreeUtils;
import com.huaao.micropolice.root.controllers.BaseController;
import com.huaao.micropolice.root.freemarker.FreemarkerTemplate;

@Controller
@RequestMapping("system/role")
public class RoleController extends BaseController{
	@Autowired
	private RoleService roleService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private JobsService jobsService;
	@Autowired
	private UserService userService;
	@Autowired
	private ButtonService buttonService;
	@Autowired
	private MenuDeptService menuDeptService;
	@Autowired
	private MenuSubjectService menuSubjectService;
	@Autowired
	private SubjectService subjectService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	@RequestMapping("index.do")
	public String index(){
		return "/system/role/index";
	}
	
	@RequestMapping("load.do")
	public ResponseEntity<String> load(String id){
		String json = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			Role role = roleService.load(id);
			map.put("role", role);
			map.put("dept", role.getDept());
			Gson gson = new GsonSimpleFilter().createBuilder()
			        .setFilterClass(Role.class).setClassIncludes("id").setClassIncludes("name").setClassIncludes("mark")
			        .setFilterClass(Dept.class).setClassIncludes("id").setClassIncludes("name")
			        .buildPreFilter()
			        .create();
			json = gson.toJson(map);
		} catch (Exception e) {
			e.printStackTrace();
			json = JsonUtil.toJson(failMap());
		}
		return super.ajaxModel(JSON, json);
	}
	
	@RequestMapping("save.do")
	public ResponseEntity<String> save(Role role){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if(StringUtils.isBlank(role.getId())){
				roleService.add(role);
			}else{
				roleService.edit(role);
			}
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("dels.do")
	public ResponseEntity<String> dels(@RequestParam(value = "ids[]") String[] ids){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			roleService.dels(ids);
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("list.do")
    public ResponseEntity<String> list() {
		String json = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			Page page = getPage();
			roleService.list(getSort(),page);
			map.put("total", page.getTotalPageNum());
			map.put("page", page.getPageNum());
			map.put("records", page.getTotalCount());
			map.put("rows",page.getResults());
			Gson gson = new GsonSimpleFilter().createBuilder()
	                .setFilterClass(Role.class).setClassIncludes("id").setClassIncludes("name").setClassIncludes("mark").setClassIncludes("dept")
	                .setFilterClass(Dept.class).setClassIncludes("id").setClassIncludes("name")
	                .buildPreFilter()
	                .create();
			json = gson.toJson(map);
		} catch (Exception e) {
			json = JsonUtil.toJson(failMap());
		}
		return super.ajaxModel(JSON, json);
    }
	
	@RequestMapping("findAllDeptJson.do")
	public ResponseEntity<String> findAllDeptJson(){
		Map<String, Object> map = new HashMap<String, Object>();
		List<Dept> depts = deptService.findAll();
		StringBuffer buff = new StringBuffer();
		TreeUtils.buildDeptTreeJson(buff,depts);
		map.put("result", buff.toString());
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("roleBind.do")
	public String roleBind(String id){
		Role role = roleService.load(id);
		List<Jobs> jobsList = jobsService.findByDeptId(role.getDept().getId());
		List<User> users = userService.findByDeptId(role.getDept().getId());
		request.setAttribute("role", role);
		request.setAttribute("jobsList", jobsList);
		request.setAttribute("users", users);
		return "/system/role/bind";
	}
	
	@RequestMapping("bindJobs.do")
	public ResponseEntity<String> bindJobs(@RequestParam(value = "jobIds[]") String[] jobIds ,@RequestParam String id){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			roleService.bindJobs(jobIds , id);
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("bindUsers.do")
	public ResponseEntity<String> bindUsers(@RequestParam(value = "allUserIds[]") String[] allUserIds ,@RequestParam(value = "ckUserIds[]") String[] ckUserIds ,@RequestParam String id){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			roleService.bindUsers(id,allUserIds,ckUserIds);
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("bindMenu.do")
	public ResponseEntity<String> bindMenu(@RequestParam(value = "ckNodes[]") String[] ckNodes ,@RequestParam String id){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			roleService.bindMenu(ckNodes ,id);
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("bindBtns.do")
	public ResponseEntity<String> bindBtns(@RequestParam(value = "ckBtnIds[]") String[] ckBtnIds,@RequestParam(value = "allBtnIds[]") String[] allBtnIds ,@RequestParam String id){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			roleService.bindBtns(ckBtnIds,allBtnIds ,id);
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("menuChange.do")
	public ResponseEntity<String> menuChange(String menuId , String roleId , String deptId){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Role role = roleService.load(roleId);
			Menu menu = menuService.load(menuId);
			List<Button> btns = buttonService.findByMenuId(menu.getId());
			Set<String> depts = menuDeptService.findDeptsIds(menu,role);
			if(!StringUtils.isBlank(deptId)){
				Set<String> subs = menuSubjectService.findSubjectIds(menu, role , deptId);
				map.put("subIds", subs);
			}
			Map<String, Object> rootMap = new HashMap<String , Object>();
			rootMap.put("btns", btns);
			rootMap.put("roleBtns", role.getButtons());
			String result = FreemarkerTemplate.process("role/menu_btn.ftl", rootMap, freeMarkerConfigurer);
			
			map.put("deptIds", depts);
			map.put("btnHtml", result);
			
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("deptChange.do")
	public ResponseEntity<String> deptChange(String menuId , String deptId ,String roleId){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<Subject> subjects = subjectService.findByDept(deptId);
			StringBuffer buff = new StringBuffer();
			TreeUtils.buildSubjectTreeJson(buff, subjects);
			map.put("result", buff.toString());
			
			Set<String> subjectIds = menuSubjectService.findSubjectIds(subjects , menuId , roleId);
			map.put("subjectIds", subjectIds);
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("bindMenuDept.do")
	public ResponseEntity<String> bindMenuDept(@RequestParam(value = "ckDepts[]") String[] ckDepts , @RequestParam String menuId , @RequestParam String id){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			menuDeptService.bind(id,menuId,ckDepts);
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
	
	@RequestMapping("bindMenuSubject.do")
	public ResponseEntity<String> bindMenuSubject(@RequestParam(value = "ckSubs[]") String[] ckSubs,@RequestParam String menuId ,@RequestParam String deptId, @RequestParam String id){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			menuSubjectService.bind(id,menuId,deptId,ckSubs);
			map = successMap();
		} catch (Exception e) {
			map = failMap();
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(map));
	}
}
